import { useRef, useState, useEffect, useCallback } from "react"
import { Button,Modal,Space,Toast } from 'antd-mobile'
import callFeedback from "../modalFeedback"
import {  PrizeComp, RuleComp, ShareComp, StuffComp, ActivityTimeComp } from "@/components/common";
import requewt from "@/utils/requewt";
import { API,REDIRECT_TITLE,REDIRECT_URL, REDIRECT_COVER,REDIRECT_DESC,BASE_PATH,MINI_P_ID,MINI_P_PATH,REDIRECT_WX_URL, PROJ_TITLE } from "@/config";
import { HC, checkENV, checkENV2 } from "@/utils";
import Router from "next/router";
import dayjs from "dayjs";
import { useCookies } from "react-cookie";
import useApp from "@/stores/useApp";
import useShare from "../hooks/useShare";
import { HelpingComp } from "../shareComp";
import PrizeBox from "./PrizeBox";
import { signIn } from "next-auth/react";

export const useToolbar = (param) => {
    // const [env, setEnv] = useState(undefined)
    const env = useApp(state => state.env)
    const updateENV = useApp(state => state.updateENV)
    const {handleAppShareToH5} = useShare()
    let flag = useRef(0)
    console.log(env)
    const user = useApp(state => state.user)
    const [cookies, setCookies] = useCookies(['name'])
      /**
   * 等待环境加载
   * @param ev
   */
  const waitForAuth = (ev) => {
    if (flag.current >= 30) {
      Toast.show({duration: 1000, content: `持续授权失败！请保证网络畅通、并在极狐小程序中打开`, position: `top`});
      return
    }
    setTimeout(() => {
      if (ev) {
        // setEnv(ev);
        return;
      }
      flag.current++;
      const resolve = checkENV();
      console.log(resolve,'resolveeeeee')
      waitForAuth(resolve);
    }, 100);
  };
  useEffect(() => {
    // waitForAuth(env)
  }, [])
    useEffect(() => {
      
        (async () => {
          // setEnv(await checkENV2())
          const env = await checkENV2()
          updateENV(env)
          if (!(['app','mini'].includes(env))) {
            Toast.show({duration: 1000, content: `持续授权失败！请保证网络畅通、并在极狐小程序中打开`, position: `top`});
          }
        })()
        
      }, [])

    const compHandler = {
        link: async (url) => {
          const env = await checkENV2();
          if (env === `mini`) {
            wx?.miniProgram.navigateTo({url: `/pages/subscribe/subscribe?id=17`})
          } else if (env === `app`) {
            const {type, value} = appTypeCheck(`https://img.qiyuan.changan.com.cn/download/index.html?channel=10012`) || {};
            appNavigate(type, value);
          }
        },
        navigate: url => navigateTo(url),
        // 打开规则
        rule: () => {
          const m = callFeedback({
            bodyClassName: `act-feedback-modal close-at-center-bottom`,
            title: <div className="text-center text-qy-bold">活动规则</div>,
            content: <div className="inner"><RuleComp /></div>,
            actions: <>
              <Button className="act-btn act-btn-bevel act-btn-bevel-2"  onClick={()=> {m.close()}}>确 认</Button>
            </>,
            closeOnAction: true,
            closeOnMaskClick: true,
            hideClose:true
          })
        },
        // 我的奖品
        prize: async () => {
          const m = callFeedback({
            hideClose:true,
            bodyClassName: `act-feedback-modal  prize-modal`,
            title:<div className="header-img-wrapper">
            我的奖品
          </div>,
            content: <div className="inner"><PrizeComp /></div>,
            actions: <>
              
            </>,
            // hideClose:true,
            closeOnAction: true,
            closeOnMaskClick: true,
          })
        },
        // 点击分享
        pressShare: (modal) => {
          return handleAppShareToH5({
            // sharephone:user.phone,
            h5Title: `${PROJ_TITLE}每日瓜分五百万枚源宝`,
            h5Desc: `我的邀请码：${user?.invite_code}，请为我助力！`
          })
          // return new Promise((resolve,reject) => {
          //   // 记录分享
          // if (env === `app`) {
          //   //
          //   const json = {
          //     shareTitle: REDIRECT_TITLE,
          //     shareUrl: REDIRECT_URL,
          //     // shareUrl: `https://head.uni.changan.com.cn/quanzi/#/zixunPreview?artId=2076`,
          //     shareImg: REDIRECT_COVER,
          //     shareDesc: REDIRECT_DESC,
          //     shareType: "3",
          //     isImg: "0",
          //     isMiniProgram: "1",
          //     userName: MINI_P_ID,
          //     path: REDIRECT_WX_URL({sharephone:user.phone}),
          //     // miniprogramType: 0,
          //   }
          //   try {
          //     // 菜单分享
          //     window.QYApp?.shareTo(JSON.stringify(json), 'shareCallBack')
          //   } catch (error) {
          //     Toast.show({content: `分享失败`})
          //     reject()
          //   }
    
          // }
          // // 小程序分享
          // else {
          //   callFeedback({
          //     bodyClassName: 'share-tips-modal',
          //     actions: [],
          //     hideClose: true,
          //     title: <div >
          //     </div>,
          //     content: <img src={`${BASE_PATH}/img/game/share_indication.png`} width='308' />
          //   })
          // }
          
          // setTimeout(() => {
          //   requewt(API.user.share).then(()=> {
          //     // modal && modal.close()
          //     Modal.clear()
          //     resolve()
          //     // global.location.reload()
          //   })
          //   // global.location.reload()
          // }, 3000);
          // })
        },
        close: () => {
          setVisible(undefined)
        },
        stuff: () => {
          const m = callFeedback({
            bodyClassName: `act-feedback-modal close-at-center-bottom`,
            content: <div className="inner"><StuffComp /></div>,
            actions: <></>,
            closeOnAction: true,
            closeOnMaskClick: true,
          })
        },
        
      }
    const closeActions = {
      app: () => {
        if (window.QYApp.closePage) {
          window?.QYApp?.closePage()
        } else {
          global?.QYApp.closeView()
        }
      },
      mini: () => {
        wx?.miniProgram.navigateBack && wx?.miniProgram.navigateBack({})
      },
      test: () => {
        Toast.show('关闭页面')
      }
    }
    /** 错误处理 */
    const handleShowMsg = (msg,callback = ()=>{}) => {
      const m = callFeedback({
        title:<div></div>,
        content: <div className="text-center text-qy-bold" dangerouslySetInnerHTML={{__html:msg||'请求失败'}} style={{fontSize:'2rem'}}></div>,
        actions:<Button className="act-btn act-btn-bevel act-btn-bevel-2" onClick={()=> {
            m.close()
            // Modal.clear()
            callback()
        }}>确 认</Button>,
        hideClose:true
    })
    }
    /**
     * 关闭页面，仅限app，小程序有效使用
     */
    const handleClosePage = async () => {
      const env = await checkENV2()
      env && closeActions[env]()

    }
    const handleShowRule = () => {
      compHandler.rule()
    }
    const handleWheel = async () => {
      Toast.show({duration:0,content:'加载中'})
      const resp = await requewt(API.lottery.draw,{method:'POST'})
    //   const resp = {
    //     "data": {
    //       money: 100,
    //     },
    //     "error_code": 0,
    //     "msg": "\u60a8\u7684\u62bd\u5956\u6b21\u6570<br/>\u5df2\u7528\u5149",
    //     "request": "POST /march1219api/gift/draw"
    // }
      Toast.clear()
      if (resp?.error_code !== 0) {
         handleShowMsg(resp.msg)
         return Promise.reject({})
      }
      return resp.data
      // const m = callFeedback({
      //   content: <Space direction="vertical" style={{"--gap":'20px'}} block>
      //     <Space direction="vertical" style={{"--gap":'10px'}} justify="center" block>
      //       {
      //         resp.data.category!==5?<><div className="text-center text-qy-bold" style={{fontSize:'2rem'}}>恭喜您</div>
      //         <div className="text-center">源宝到手{resp.data.money}个</div></>:<div className="text-center text-qy-bold" style={{fontSize:'2rem'}}>谢谢参与</div>
      //       }
            
      //     </Space>
      //     <div className="text-center">
      //     每成功邀请一名首次注册启源APP\小程序新朋友 即可新增一次游戏机会，获取海量源宝积分
      //     </div>
      //   </Space>,
      //   actions: [
      //     <Button key="prize" className="act-btn act-btn-bevel" onClick={() => {
      //       m.close()
      //       handleShowPrize()
      //     }}>查看奖品</Button>,
      //     <Button key="share" className="act-btn act-btn-bevel" onClick={()=> {
      //       m.close()
      //       handleShare()
      //     }}>立即邀请</Button>
      //   ]
      // })
    }
    /** 展示我的奖品 */
    const handleShowPrize = async () => {
      compHandler.prize()
      // const m = callFeedback({
      //   hideClose:true,
      //   bodyClassName: `act-feedback-modal  prize-modal`,
      //   title:<div className="header-img-wrapper">
      //   我的奖品
      // </div>,
      //   content: <div className="inner"><PrizeComp /></div>,
      //   actions: <>
          
      //   </>,
      //   // hideClose:true,
      //   closeOnAction: true,
      //   closeOnMaskClick: true,
      // })
    }
    /** 分享 */
    const handleShare = () => {
      const m = callFeedback({
        title: <div >
          <img className="header-img" src={`${BASE_PATH}/img/game/share-modal-title.png`} width='84' />
        </div>,
        hideClose:true,
        content: <ShareComp />,
        actions: [
          <Button key="back" className="act-btn act-btn-bevel act-btn-bevel-2" onClick={()=> m.close()}>返回</Button>,
          <Button key="share" className="act-btn act-btn-bevel share-btn" onClick={compHandler.pressShare}>立即邀请</Button>
        ]
      })
      
    }
    /** 人机验证 */
    const humanCheck = async (values, callback) => {
      if (!values) return;
      const options = {
        method: `POST`,
        headers: {"Content-Type": `multipart/form-data`},
        body: {captchaVerifyParam:values}
      }
      const resp = await requewt(API.user.check, options);
      if (resp?.error_code !== 0 || resp?.[`msg`] !== `ok`) {
        await callFeedback({
          hideClose:true,
          title: <div></div>,
          content: <div dangerouslySetInnerHTML={{__html:resp?.msg || `验证失败`}} className="text-qy-bold text-center" style={{fontSize:'2rem'}}></div>,
          actions: [<Button key="confirm" className="act-btn act-btn-bevel " onClick={()=> Modal.clear()}>确 定</Button>]
        });
        // param?.setVisible(false);
        return;
      }

      const {auth} = cookies || {};
      await signIn("credentials", {
        token: auth, redirect: false
      });

      // reloadSession()
      // window.location.href = `/game/k`
      if (callback) {
        callback()
      }
    }
    const showHelpingHand = () => {
      const m = callFeedback({
        title: <div >
          <img className="header-img" src={`${BASE_PATH}/img/game/share-modal-title.png`} width='84' />
        </div>,
        hideClose:true,
        content: <HelpingComp />,
        actions: <></>
      })
    }
    /** 助力 */
    const handleHelpingHand = useCallback(() => {
      if (user.is_robot) {
        param?.setVisible(true)
        setTimeout(() => {
          HC((result) => {
            humanCheck(result, () => {
              param?.setVisible(false)
              showHelpingHand()
            })
          })
        }, 300)
        return
      }
      showHelpingHand()
      
    }, [param?.setVisible,user])
    /** 超出活动时间 */
    const handleActivityTime = () => {
      const m = callFeedback({
        bodyClassName: `act-feedback-modal close-at-center-bottom`,
        title: <div className="text-center text-qy-bold">公 告<img className="header-img" src={`${BASE_PATH}/img/game/share-modal-title.png`} width='84' /></div>,
        content: <div className="inner"><ActivityTimeComp /></div>,
        actions: <>
          <Button className="act-btn act-btn-bevel act-btn-bevel-2"  onClick={()=> {handleClosePage}}>退 出</Button>
        </>,
        closeOnAction: false,
        closeOnMaskClick: false,
        hideClose:true
      })
    }
    /** 展示抽奖弹窗 */
    const handlePrizeModal = () => {

    }

      return {
        toolbarHandler: compHandler,
        handleClosePage,
        handleShowRule,
        handleShowPrize,
        handleShare,
        handleShowMsg,
        handleHelpingHand,
        handleWheel,
        handleActivityTime,
        humanCheck
      }
}